const fs = require('fs');
const SVGIcons2SVGFontStream = require('svgicons2svgfont');
const svg2ttf = require('svg2ttf');
const ttf2eot = require('ttf2eot');
const ttf2woff = require('ttf2woff');
const ttf2woff2 = require('ttf2woff2');


var svg2font = {
  unicodeStartNumber: 10000,
  fontCodeList: [],
  fontNameList: [],
  dist: '',
  svgDir: '',
  build(svgDir, dist) {
    return new Promise((resolve, reject) => {
      this.svgDir = svgDir;
      this.dist = dist;

      this.toSvgFont().then(() => {
        this.toTTF().then(() => {
          this.toEot()
          this.toWoff()
          this.toWoff2()
          resolve()
        })
      })

    })
  },
  toSvgFont() {
    return new Promise((resolve, reject) => {
      var This = this;
      const fontStream = new SVGIcons2SVGFontStream({
        fontName: 'svg-icon'
      });

      fontStream.pipe(fs.createWriteStream(this.dist + '/svgfont.svg'))
        .on('finish', function() {
          console.log('svgfont.svg 生成成功')
          resolve();
        })
        .on('error', function(err) {
          console.log(err);
          reject();
        });

      fs.readdir(this.svgDir, (err, files) => {
        files.forEach(file => {
          This.unicodeStartNumber++;

          var fileName = file.split('.')[0];
          const glyph = fs.createReadStream(this.svgDir + '/' + file);
          const unicode = String.fromCharCode(This.unicodeStartNumber);

          var code =  Number(This.unicodeStartNumber).toString(16);
          This.fontCodeList.push(code);
          This.fontNameList.push(fileName);

          glyph.metadata = {
            unicode: [unicode[0]],
            name: fileName
          };

          fontStream.write(glyph);
        })
        fontStream.end();

      })
    })
  },
  toTTF() {
    return new Promise((resolve, reject) => {
      let ttf = svg2ttf(fs.readFileSync(this.dist + '/svgfont.svg', 'utf8'), {});
      fs.writeFile(this.dist + '/svgfont.ttf', new Buffer(ttf.buffer), (err, data) => {
        if (err) {
          console.log(err);
          reject()
          return false;
        }

        console.log('svgfont.ttf 生成成功')
        resolve()
      });

    })
  },
  toEot() {
    var input = fs.readFileSync(this.dist + '/svgfont.ttf');

    var ttf = new Uint8Array(input);
    var eot = new Buffer(ttf2eot(ttf).buffer);

    fs.writeFileSync(this.dist + '/svgfont.eot', eot);

    console.log('svgfont.eot 生成成功')
  },
  toWoff() {
    var input = fs.readFileSync(this.dist + '/svgfont.ttf');
    var ttf = new Uint8Array(input);
    var woff = Buffer.from ? Buffer.from(ttf2woff(ttf).buffer) : new Buffer(ttf2woff(ttf).buffer);

    fs.writeFileSync(this.dist + '/svgfont.woff', woff);

    console.log('svgfont.woff 生成成功')
  },
  toWoff2() {
    var input = fs.readFileSync(this.dist + '/svgfont.ttf');
    fs.writeFileSync(this.dist + '/svgfont.woff2', ttf2woff2(input));

    console.log('svgfont.woff2 生成成功')
  }
}

module.exports = svg2font;